import {
  getItems,
  getItemById,
  createItem,
  updateItem,
  updateItems,
  deleteItem,
  deleteItems,
} from "@/api/directus";

/** 集合名 */
export const COLLECTION_DEFAULT_SEARCH = "default_search_keyword" as const;

/** 状态 */
export type DefaultKeywordStatus = "published" | "draft" | "archived";

/** 记录结构 */
export interface DefaultKeywordItem {
  id: number | string;
  query?: string;
  status?: DefaultKeywordStatus;
  sence?: string;
  date_created?: string;
  date_updated?: string;
  user_created?: any;
  user_updated?: any;
}

/** 列表入参/出参 */
export interface DefaultKeywordListParams {
  page?: number;
  pageSize?: number;
  keyword?: string;
  sort?: string | string[];
  excludeStatus?: DefaultKeywordStatus;
  signal?: AbortSignal;
}
export interface DefaultKeywordListResult {
  list: DefaultKeywordItem[];
  total: number;
}

/** 列表 */
export async function listDefaultKeywords(
  params: DefaultKeywordListParams = {}
): Promise<DefaultKeywordListResult> {
  const {
    page = 1,
    pageSize = 10,
    keyword,
    sort = "-id",
    excludeStatus = "archived",
    signal,
  } = params;

  const filter: Record<string, any> = {};
  if (excludeStatus) filter.status = { _neq: excludeStatus };
  if (keyword && keyword.trim()) filter.query = { _contains: keyword.trim() };

  const fields = ["id", "query", "status", "sence"];
  const { data, meta } = await getItems<DefaultKeywordItem>(COLLECTION_DEFAULT_SEARCH, {
    page,
    limit: pageSize,
    sort,
    fields,
    filter,
    meta: "filter_count",
    signal,
  });

  return {
    list: data,
    total: (meta as any)?.filter_count ?? 0,
  };
}

/** 详情 */
export function getDefaultKeywordById(id: number | string, signal?: AbortSignal) {
  return getItemById<DefaultKeywordItem>(COLLECTION_DEFAULT_SEARCH, id, {
    fields: ["id", "query", "status", "sence", "date_created"],
    signal,
  });
}

/** 新增 */
export function createDefaultKeyword(payload: Partial<DefaultKeywordItem>) {
  return createItem<DefaultKeywordItem>(COLLECTION_DEFAULT_SEARCH, payload);
}

/** 更新 */
export function updateDefaultKeyword(id: number | string, payload: Partial<DefaultKeywordItem>) {
  return updateItem<DefaultKeywordItem>(COLLECTION_DEFAULT_SEARCH, id, payload);
}

/** 批量更新 */
export function updateDefaultKeywords(
  rows: Array<Partial<DefaultKeywordItem> & { id: string | number }>
) {
  return updateItems<DefaultKeywordItem>(COLLECTION_DEFAULT_SEARCH, rows);
}

/** 启/停 */
export function enableDefaultKeyword(id: number | string) {
  return updateDefaultKeyword(id, { status: "published" });
}
export function disableDefaultKeyword(id: number | string) {
  return updateDefaultKeyword(id, { status: "draft" });
}

/** 删除 */
export function removeDefaultKeyword(id: number | string) {
  return deleteItem(COLLECTION_DEFAULT_SEARCH, id);
}

/** 批量删除 */
export function removeDefaultKeywords(ids: Array<number | string>) {
  return deleteItems(COLLECTION_DEFAULT_SEARCH, ids);
}

/* ------------------------------------------------------------------
   —— 下面开始：应用频道（vertical_category）接口 —— 
   不影响上面的 default_search 代码；沿用你的 CRUD 封装与风格
-------------------------------------------------------------------*/

/** 应用频道集合名 */
export const COLLECTION_VERTICAL_CATEGORY = "vertical_category" as const;

/** 频道记录结构：与你抓包字段一致（id / query / value） */
export interface VerticalCategoryItem {
  id: number | string;
  query?: string;
  value?: string | number;
  date_created?: string;
  date_updated?: string;
  user_created?: any;
  user_updated?: any;
}

/** 列表入参/出参 */
export interface VerticalCategoryListParams {
  page?: number;
  pageSize?: number;   // 抓包是 25
  keyword?: string;    // 模糊匹配 query（需要同时搜 value 可改为 _or，见下注释）
  sort?: string | string[]; // 抓包为 id 升序
  signal?: AbortSignal;
}
export interface VerticalCategoryListResult {
  list: VerticalCategoryItem[];
  total: number;
}

/** 列表（等价于抓包：limit=25&fields[]=query&fields[]=value&fields[]=id&sort[]=id&page=1） */
export async function listVerticalCategories(
  params: VerticalCategoryListParams = {}
): Promise<VerticalCategoryListResult> {
  const {
    page = 1,
    pageSize = 25,
    keyword,
    sort = "id",
    signal,
  } = params;

  const filter: Record<string, any> = {};
  if (keyword && keyword.trim()) {
    filter.query = { _contains: keyword.trim() };
    // 如果你需要同时匹配 value，则改为：
    // filter._or = [
    //   { query: { _contains: keyword.trim() } },
    //   { value: { _contains: keyword.trim() } },
    // ];
  }

  const fields = ["id", "query", "value"];

  const { data, meta } = await getItems<VerticalCategoryItem>(
    COLLECTION_VERTICAL_CATEGORY,
    {
      page,
      limit: pageSize,
      sort,
      fields,
      filter,
      meta: "filter_count", // 直接拿到总数
      signal,
    }
  );

  return {
    list: data,
    total: (meta as any)?.filter_count ?? 0,
  };
}

/** 详情 */
export function getVerticalCategoryById(id: number | string, signal?: AbortSignal) {
  return getItemById<VerticalCategoryItem>(COLLECTION_VERTICAL_CATEGORY, id, {
    fields: ["id", "query", "value", "date_created", "date_updated"],
    signal,
  });
}

/** 新增 */
export function createVerticalCategory(payload: Partial<VerticalCategoryItem>) {
  return createItem<VerticalCategoryItem>(COLLECTION_VERTICAL_CATEGORY, payload);
}

/** 更新 */
export function updateVerticalCategory(id: number | string, payload: Partial<VerticalCategoryItem>) {
  return updateItem<VerticalCategoryItem>(COLLECTION_VERTICAL_CATEGORY, id, payload);
}

/** 批量更新 */
export function updateVerticalCategories(
  rows: Array<Partial<VerticalCategoryItem> & { id: string | number }>
) {
  return updateItems<VerticalCategoryItem>(COLLECTION_VERTICAL_CATEGORY, rows);
}

/** 删除 */
export function removeVerticalCategory(id: number | string) {
  return deleteItem(COLLECTION_VERTICAL_CATEGORY, id);
}

/** 批量删除 */
export function removeVerticalCategories(ids: Array<number | string>) {
  return deleteItems(COLLECTION_VERTICAL_CATEGORY, ids);
}

/** 下拉选项/远程搜索 */
export async function fetchVerticalCategoryOptions(params: {
  keyword?: string;
  page?: number;
  pageSize?: number;
  signal?: AbortSignal;
} = {}) {
  const { keyword, page = 1, pageSize = -1, signal } = params;

  const filter: Record<string, any> = {};
  if (keyword && keyword.trim()) {
    filter.query = { _contains: keyword.trim() };
  }

  const { data } = await getItems<Pick<VerticalCategoryItem, "id" | "query" | "value">>(
    COLLECTION_VERTICAL_CATEGORY,
    {
      page,
      limit: pageSize,
      sort: "id",
      fields: ["id", "query", "value"],
      filter,
      signal,
    }
  );

  return data;
}
